package program;

import kernel.exception.OSException;
import kernel.process.AbstractProcess;
import kernel.process.AbstractProcessHeader;

/**
 * Uniq process.
 * For more see man() method.
 * @author Petr Hajek, Veronika Vencurikova
 *
 */
public class Uniq extends AbstractProcess {

	public Uniq(AbstractProcessHeader header, long pid) {
		super(header, pid);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String doJob(String input) throws OSException {
		if (input.equals("") && this.params.size() < 1) {
			throw new OSException(OSException.NO_ARGS);
		}
		
		String out = "";
		
		String[] parsedIn;
		
		if (this.params.size() > 0 && this.input.equals("")) {
			parsedIn = new String[this.params.size()];
			for (int i = 0; i < this.params.size(); i++) {
				parsedIn[i] = this.params.get(i);
			}
		}
		
		else {
			parsedIn = input.split("\n");
		}
		int i = 0;
		for (; i < parsedIn.length; ) {
			String line = parsedIn[i];
			out += line + "\n";
			i++;
			while (i < parsedIn.length && parsedIn[i].equals(line)) {
				i++;
			}
		}
		
		return out;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String continueJob() throws OSException {
		this.shouldEnd = true;
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String finalizeJob() throws OSException {
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean needParams() {
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void kill() throws OSException {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String man(String command) {
	String man = "";
		
		man += "    removes duplicate lines form a sorted file\n";
		man += "\n";
		man += "Command syntax:\n";
		man += "    uniq [FILE]\n";
		
		return man;
	}

}
